package com.yssoft.service.purchase;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.DecoderException;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartRequest;

import com.yssoft.entity.inventory.TInstockApply;
import com.yssoft.entity.inventory.TInstockApplyDetail;
import com.yssoft.entity.purchase.TPurchaseDetail;
import com.yssoft.entity.purchase.TPurchaseInfo;
import com.yssoft.entity.purchase.TRecipientAtt;
import com.yssoft.entity.purchase.TRecipientDetail;
import com.yssoft.entity.traceability.TTraceGather;
import com.yssoft.entity.traceability.TTraceGatherAtt;
import com.yssoft.entity.traceability.TTraceQuota;
import com.yssoft.mapper.inventory.TInstockApplyDetailMapper;
import com.yssoft.mapper.inventory.TInstockApplyMapper;
import com.yssoft.mapper.inventory.TWarehouseMapper;
import com.yssoft.mapper.purchase.TPurchaseDetailMapper;
import com.yssoft.mapper.purchase.TPurchaseInfoMapper;
import com.yssoft.mapper.purchase.TRecipientAttMapper;
import com.yssoft.mapper.purchase.TRecipientDetailMapper;
import com.yssoft.mapper.traceability.TTraceGatherAttMapper;
import com.yssoft.mapper.traceability.TTraceGatherMapper;
import com.yssoft.mapper.traceability.TTraceProcessMapper;
import com.yssoft.mapper.traceability.TTraceQuotaMapper;
import com.yssoft.utils.AppUserHelper;
import com.yssoft.utils.AppUtil;
import com.yssoft.utils.UploadFile;
import com.yssoft.vo.TRecipientAttVo;

@Service
public class RecipientDetailService {

	private static Logger logger=Logger.getLogger(RecipientDetailService.class);
	
	@Resource
	private TRecipientDetailMapper tRecipientDetailMapper;
	@Resource
	private TRecipientAttMapper tRecipientAttMapper;
	@Resource
	private TPurchaseInfoMapper tPurchaseInfoMapper;
	@Resource
	private TPurchaseDetailMapper tPurchaseDetailMapper;
	@Resource
	private TInstockApplyMapper tInstockApplyMapper;
	@Resource
	private TWarehouseMapper tWarehouseMapper;
	@Resource
	private TInstockApplyDetailMapper tInstockApplyDetailMapper;
	@Resource
	private TTraceProcessMapper tTraceProcessMapper;
	@Resource
	private TTraceQuotaMapper tTraceQuotaMapper;
	@Resource
	private TTraceGatherMapper tTraceGatherMapper;
	@Resource
	private TTraceGatherAttMapper tTraceGatherAttMapper;

	/**
	 * 查询待收货列表
	 * @param pageSize 
	 * @param currentPage 
	 * @param page
	 * @param limit
	 * @param userId
	 * @param supplierId
	 * @param supplyTime
	 * @return
	 */
	public List<Map<String, Object>> toReceiveList(int currentPage, int pageSize, String userId, String supplierId,
			String supplyTime, HttpServletRequest request) {
		/*分页整理*/
		int start = (currentPage-1) * pageSize;
		int end = pageSize;
		/*查询条件整理*/
		Map<String, Object> param = new HashMap<>();
		param.put("stat", 1);	//状态-待收货
//		param.put("userId", userId);	//用户id
		param.put("tEId", AppUserHelper.getCurrentCompanyId(request));
		param.put("supplierId", supplierId);	//供应商id
		param.put("supplyTime", supplyTime);	//采购单到货日期
		param.put("start",start);
		param.put("end", end);
		
		List<Map<String, Object>> purchaseList = tPurchaseInfoMapper.queryPurchaseList(param);
		Iterator<Map<String, Object>> iter = purchaseList.iterator();  
		while(iter.hasNext()){  
		    Map<String, Object> map = iter.next(); 
		    param.put("purchaseId", map.get("info_id"));
			List<Map<String, Object>> purchaseDetailList = tPurchaseDetailMapper.queryPurchaseDetailList(param);
			if(purchaseDetailList.size() > 0){
				map.put("purchaseDetailList", purchaseDetailList);
			}
			else {
				iter.remove();
			}
		}
		return purchaseList;
	}
	
	/**
	 * 查询待收货列表
	 * @param pageSize 
	 * @param currentPage 
	 * @param page
	 * @param limit
	 * @param userId
	 * @param supplierId
	 * @param supplyTime
	 * @return
	 */
	public List<Map<String, Object>> receiveList(int currentPage, int pageSize, String userId, String supplierId,
			String supplyTime, HttpServletRequest request) {
		/*分页整理*/
		int start = (currentPage-1) * pageSize;
		int end = pageSize;
		/*查询条件整理*/
		Map<String, Object> param = new HashMap<>();
		param.put("stat", 2);	//状态-已收货
//		param.put("userId", userId);	//用户id
		param.put("tEId", AppUserHelper.getCurrentCompanyId(request));
		param.put("supplierId", supplierId);	//供应商id
		param.put("supplyTime", supplyTime);	//采购单到货日期
		param.put("start",start);
		param.put("end", end);
		
		List<Map<String, Object>> purchaseList = tPurchaseInfoMapper.queryPurchaseList(param);
		Iterator<Map<String, Object>> iter = purchaseList.iterator();  
		while(iter.hasNext()){  
		    Map<String, Object> map = iter.next(); 
		    param.put("purchaseId", map.get("info_id"));
			List<Map<String, Object>> purchaseDetailList = tPurchaseDetailMapper.queryPurchaseDetailList(param);
			if(purchaseDetailList.size() > 0){
				map.put("purchaseDetailList", purchaseDetailList);
			} else {
				iter.remove();  
			}
		}
		return purchaseList;
	}

	/**
	 * 保存收货单
	 * @param tRecipientDetail
	 * @param tRecipientAttVo
	 * @param qualifieds 
	 * @param transactions 
	 * @param transactionPicfile
	 * @param qualifiedpicfile
	 * @throws ParseException 
	 */
	@Transactional(rollbackFor = Exception.class)
	public void receipt(TRecipientDetail tRecipientDetail, TRecipientAttVo tRecipientAttVo, HttpServletRequest request) throws ParseException {
		/*整理收货详细信息*/
		String code = System.currentTimeMillis() + "";
		tRecipientDetail.setCode(code);
		tRecipientDetail.setCreateTime(new Date());
		tRecipientDetail.setDeleteFlag("0");
		tRecipientDetail.setCreatorId(AppUserHelper.getCurrentUserId(request));
		tRecipientDetail.setCreatorName(AppUserHelper.getCurrentUserName(request));
		tRecipientDetail.setDeptId(AppUserHelper.getCurrentDeptId(request));
		tRecipientDetail.setDeptName(AppUserHelper.getCurrentDeptName(request));
		tRecipientDetail.settEId(AppUserHelper.getCurrentCompanyId(request));
		
		tRecipientAttVo.setTransactionType("1");
		tRecipientAttVo.setQualifiedType("2");
		/*保存收货详细信息*/
		tRecipientDetailMapper.myInsertSelective(tRecipientDetail);
		/*获取收货详细信息Id*/
		Integer recipientDetailId = tRecipientDetail.getId();
		/*整理附件表基本信息*/
		TRecipientAtt recipientAtt = new TRecipientAtt();
		recipientAtt.settRId(recipientDetailId);
		recipientAtt.setDeleteFlag("0");
		recipientAtt.settEId(tRecipientDetail.gettEId());
		recipientAtt.setCreateTime(tRecipientDetail.getCreateTime());
		recipientAtt.setDeptId(tRecipientDetail.getDeptId());
		recipientAtt.setDeptName(tRecipientDetail.getDeptName());
		
		MultipartRequest mRequest=(MultipartRequest)request;
		Iterator<String> fileNames = mRequest.getFileNames();
		while(fileNames.hasNext()){
			MultipartFile file = mRequest.getFile(fileNames.next());
			Map<String,Object> urlMap = null;
            try {
                urlMap = UploadFile.compressUploadedFile(file);
            } catch (Exception e) {
            	logger.info( "上传图片失败" + e.getMessage());
            }
            if(file.getName().indexOf("transaction") != -1){
            	/*整理交易凭证信息*/
            	recipientAtt.setType(tRecipientAttVo.getTransactionType());
        		recipientAtt.setAttImg(urlMap.get("fileName")+"");
        		recipientAtt.setAttTimg(urlMap.get("thumbnails")+"");
        		tRecipientAttMapper.myInsertSelective(recipientAtt);
            }
            if(file.getName().indexOf("qualified") != -1){
            	/*整理合格证明信息*/
            	recipientAtt.setType(tRecipientAttVo.getQualifiedType());
    			recipientAtt.setAttImg(urlMap.get("fileName")+"");
        		recipientAtt.setAttTimg(urlMap.get("thumbnails")+"");
    			tRecipientAttMapper.myInsertSelective(recipientAtt);
            }
		}
			
		/*List<MultipartFile> trans = mRequest.getFiles("transaction");
		for(MultipartFile file : trans){
			Map<String,Object> urlMap = null;
			try {
                urlMap = UploadFile.compressUploadedFile(file);
            } catch (Exception e) {
            	logger.info( "上传图片失败" + e.getMessage());
            }
			recipientAtt.setType(tRecipientAttVo.getTransactionType());
    		recipientAtt.setAttImg(urlMap.get("fileName")+"");
    		recipientAtt.setAttTimg(urlMap.get("thumbnails")+"");
    		tRecipientAttMapper.myInsertSelective(recipientAtt);
		}
		
		List<MultipartFile> qualified = mRequest.getFiles("qualified");
		for(MultipartFile file : qualified){
			Map<String,Object> urlMap = null;
			try {
                urlMap = UploadFile.compressUploadedFile(file);
            } catch (Exception e) {
            	logger.info( "上传图片失败" + e.getMessage());
            }
			recipientAtt.setType(tRecipientAttVo.getQualifiedType());
			recipientAtt.setAttImg(urlMap.get("fileName")+"");
    		recipientAtt.setAttTimg(urlMap.get("thumbnails")+"");
			tRecipientAttMapper.myInsertSelective(recipientAtt);
		}*/
		/*判断是否为收货*/
		if("1".equals(tRecipientDetail.getStat())){
			/*收货详细信息保存成功，修改采购单详细验收数量*/
			TPurchaseDetail purchaseDetail = tPurchaseDetailMapper.selectByPrimaryKey(tRecipientDetail.gettDdId());
			if(purchaseDetail.getAcceptQuantity() != null){
				BigDecimal purchaseDetailSum = purchaseDetail.getAcceptQuantity().add(tRecipientDetail.getActualQuantity());
				purchaseDetail.setAcceptQuantity(purchaseDetailSum);
			} else {
				purchaseDetail.setAcceptQuantity(tRecipientDetail.getActualQuantity());
			}
			/*判断  采购数量 == 验收数量  相等修改采购单详细状态*/
			if(purchaseDetail.getQuantity().compareTo(purchaseDetail.getAcceptQuantity()) != 1){
				purchaseDetail.setStat("2");
			}
			/*修改采购单详细信息*/
			tPurchaseDetailMapper.updateByPrimaryKeySelective(purchaseDetail);
			/*查看状态不为"已收货"采购单详细信息*/
			Map<String, Object> param = new HashMap<>();
			param.put("tPId", tRecipientAttVo.gettPId());
			param.put("stat","1");
			List<Map<String, Object>> tPurchaseDetailList = tPurchaseDetailMapper.queryPurchaseDetailNoTwo(param);
			/*修改采购单状态*/
			if(tPurchaseDetailList.size() == 0){
				TPurchaseInfo tPurchaseInfo = new TPurchaseInfo();
				tPurchaseInfo.setId(tRecipientAttVo.gettPId());
				tPurchaseInfo.setStat("2");
				tPurchaseInfoMapper.updateByPrimaryKeySelective(tPurchaseInfo);
			}
			
			/*生成入库申请单*/
			TInstockApply tInstockApply = new TInstockApply();
			tInstockApply.setCode("RKS" + System.currentTimeMillis());
			tInstockApply.setSourceType("2");
			tInstockApply.setInspStat("0");
			tInstockApply.setQuantity(tRecipientDetail.getActualQuantity());
			tInstockApply.settSourceId(recipientDetailId);
			tInstockApply.settWarehouseId(tRecipientDetail.gettWarehouseId());
			tInstockApply.setStat("1");
			tInstockApply.setDeleteFlag("0");
			tInstockApply.setCreatorId(tRecipientDetail.getCreatorId());
			tInstockApply.setCreatorName(tRecipientDetail.getCreatorName());
			tInstockApply.settEId(tRecipientDetail.gettEId());
			tInstockApply.setCreateTime(tRecipientDetail.getCreateTime());
			tInstockApply.setDeptId(tRecipientDetail.getDeptId());
			tInstockApply.setDeptName(tRecipientDetail.getDeptName());
			
			tInstockApplyMapper.insertSelective(tInstockApply);
			/*生成入库申请单明细*/
			TInstockApplyDetail tInstockApplyDetail = new TInstockApplyDetail();
			tInstockApplyDetail.setSourceType("2"); //来源-采购
			tInstockApplyDetail.setpType("3");	//类型-物料
			tInstockApplyDetail.setQuantity(tRecipientDetail.getActualQuantity());
			tInstockApplyDetail.settSourceId(recipientDetailId);
			tInstockApplyDetail.settWarehouseId(tRecipientDetail.gettWarehouseId());
			tInstockApplyDetail.setStat("1");
			tInstockApplyDetail.settMId(tRecipientDetail.gettMId());
			tInstockApplyDetail.settInstockAppId(tInstockApply.getId());
			tInstockApplyDetail.setDeleteFlag("0");
			tInstockApplyDetail.setCreatorId(tRecipientDetail.getCreatorId());
			tInstockApplyDetail.setCreatorName(tRecipientDetail.getCreatorName());
			tInstockApplyDetail.settEId(tRecipientDetail.gettEId());
			tInstockApplyDetail.setCreateTime(tRecipientDetail.getCreateTime());
			tInstockApplyDetail.setDeptId(tRecipientDetail.getDeptId());
			tInstockApplyDetail.setDeptName(tRecipientDetail.getDeptName());
			
			tInstockApplyDetailMapper.insertSelective(tInstockApplyDetail);
		}
	}

	/**
	 * 进货记录查看
	 * @param tDdId
	 * @return
	 */
	public Map<String, Object> queryReceiptRecord(String tDdId, HttpServletRequest request) {
		/*查询采购单信息*/
		Map<String, Object> receiptRecord = tPurchaseDetailMapper.queryReceiptRecord(Integer.parseInt(tDdId));
		/*查询采购单详细信息*/
		Map<String, Object> param = new HashMap<>();
		param.put("tDdId", tDdId);
		param.put("tEId", AppUserHelper.getCurrentCompanyId(request));
		List<Map<String, Object>> purchaseDetailList = tPurchaseDetailMapper.queryPurchaseDetailList(param);
		/*查询收货单信息*/
		List<Map<String, Object>> receiptList = tRecipientDetailMapper.selectByPurchaseDetailId(Integer.parseInt(tDdId));
		for(Map<String, Object> receiptMap : receiptList){
			/*查询收货单详细附件*/
			TRecipientAtt tRecipientAtt = new TRecipientAtt();
			tRecipientAtt.setDeleteFlag("0");
			tRecipientAtt.setType("1");
			tRecipientAtt.settRId(Integer.parseInt(receiptMap.get("id").toString()));
			List<TRecipientAtt> attList1 = tRecipientAttMapper.select(tRecipientAtt);
			if(attList1.size() > 0){
				receiptMap.put("tRecipientAtt1", attList1);
			}
			tRecipientAtt.setType("2");
			List<TRecipientAtt> attList2 = tRecipientAttMapper.select(tRecipientAtt);
			if(attList2.size() > 0){
				receiptMap.put("tRecipientAtt2", attList2);
			}
		}
		if(purchaseDetailList.size() > 0){
			purchaseDetailList.get(0).put("receiptList", receiptList);
 			receiptRecord.put("purchaseDetail", purchaseDetailList.get(0));
		}
		return receiptRecord;
	}
	
	/**
	 * 采购单查看
	 * @param pageSize 
	 * @param currentPage 
	 * @param endTime 
	 * @param startTime 
	 * @param tDdId
	 * @return
	 */
	public List<Map<String, Object>> queryReceiptRecordList(int currentPage, int pageSize, String startTime, String endTime, HttpServletRequest request) {
		/*分页整理*/
		int start = (currentPage-1) * pageSize;
		/*查询条件整理*/
		Map<String, Object> param = new HashMap<>();
		param.put("tEId",AppUserHelper.getCurrentCompanyId(request));
		param.put("startTime",startTime);
		param.put("endTime",endTime);
		param.put("start",start);
		param.put("end", pageSize);
		/*查询收货单信息列表*/
		List<Map<String, Object>> receiptList = tRecipientDetailMapper.selectDetailList(param);
		for(Map<String, Object> map : receiptList){
			/*查询收货单详细附件*/
			TRecipientAtt tRecipientAtt = new TRecipientAtt();
			tRecipientAtt.setDeleteFlag("0");
			tRecipientAtt.setType("1");
			tRecipientAtt.settRId(Integer.parseInt(map.get("id").toString()));
			List<TRecipientAtt> attList1 = tRecipientAttMapper.select(tRecipientAtt);
			if(attList1.size() > 0){
				map.put("tRecipientAtt1", attList1);
			}
			tRecipientAtt.setType("2");
			List<TRecipientAtt> attList2 = tRecipientAttMapper.select(tRecipientAtt);
			if(attList2.size() > 0){
				map.put("tRecipientAtt2", attList2);
			}
		}
		return receiptList;
	}
	
	public Date addDate(Date date,long day) throws ParseException {
		 long time = date.getTime(); // 得到指定日期的毫秒数
		 day = day*24*60*60*1000; // 要加上的天数转换成毫秒数
		 time+=day; // 相加得到新的毫秒数
		 return new Date(time); // 将毫秒数转换成日期
	}

	/**
	 * 图片上传
	 * @param mFile
	 * @return
	 */
	public Map<String, Object> compressUploadedFile(MultipartFile mFile) {
		Map<String, Object> fileNames = UploadFile.compressUploadedFile(mFile);
		return fileNames;
	}

	/**
	 * 查询仓库列表
	 * @param tCId 
	 * @param request
	 * @return
	 */
	public List<Map<String,Object>> queryWarehouseList(Integer tCId, HttpServletRequest request) {
		Map<String,Object> param = new HashMap<>();
		param.put("cId",tCId);
		param.put("companyId", AppUserHelper.getCurrentCompanyId(request));
		List<Map<String,Object>> list = tWarehouseMapper.selectWarehouseByCId(param);
		return list;
	}

	/**
	 * 获取溯源过程信息
	 * @author 戈超
	 * @return
	 */
	public List<Map<String, Object>> findTechnologyByProduct(HttpServletRequest request) {
		Map<String,Object> param = new HashMap<>();
		param.put("deleteFlag", "0");
		param.put("tEId", AppUserHelper.getCurrentCompanyId(request));
		return tTraceProcessMapper.queryTraceProcess(param);
	}

	/**
	 * 根据溯源过程查询工艺的指标及指标值
	 * @param string
	 * @return
	 */
	public List<Map<String, Object>> findIndexAndValueByProcessingTechnic(String technologyId, String recipientId) {
		Map<String,Object> param = new HashMap<>();
		param.put("processId", technologyId);
		param.put("recipientId", recipientId);
		return tTraceQuotaMapper.queryTraceQuotaList(param);
	}

	/**
	 * 修改溯源指标值信息和附件的信息
	 * @author 戈超
	 * @param indicatorIds
	 * @param recipientId
	 * @param request
	 * @return
	 * @throws IOException
	 * @throws DecoderException
	 * @throws ParseException
	 */
	public Object editTechnologyIndicators(String[] indicatorIds, String recipientId, HttpServletRequest request) throws IOException, DecoderException, ParseException {
		SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat dateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (indicatorIds == null || indicatorIds.length <= 0) {
            return AppUtil.returnMapJson("0", "请传递溯源指标的id", null);
        }
        MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
        for (int i = 0; i < indicatorIds.length; i++) {
            
            TTraceQuota tTraceQuota = null;
            MultipartFile mFile2 = mRequest.getFile(indicatorIds[i] + "Value");
            try {
            	tTraceQuota = tTraceQuotaMapper.selectByPrimaryKey(Integer.parseInt(indicatorIds[i]));
            } catch (NumberFormatException e) {
                return AppUtil.returnMapJson("0", "溯源指标表的id类型转换错误", null);
            }
            
            String valuesid = request.getParameter(indicatorIds[i] + "valuesid");
            TTraceGather tTraceGather = null;
            if (valuesid != null && valuesid.length() > 0) {//修改以前的有值的
                //溯源指标值
            	tTraceGather = tTraceGatherMapper.selectByPrimaryKey(Integer.parseInt(valuesid));
            } else {
            	tTraceGather = new TTraceGather();
            	tTraceGather.setDeptId(AppUserHelper.getCurrentDeptId(request));
            	tTraceGather.setDeptName(AppUserHelper.getCurrentDeptName(request));
            	tTraceGather.settEId(AppUserHelper.getCurrentUserId(request));
                tTraceGather.settQuotaId(Integer.parseInt(indicatorIds[i]));
                tTraceGather.settRecipientId(Integer.parseInt(recipientId));
                tTraceGather.setCreateTime(new Date());
                tTraceGather.setCreatorId(AppUserHelper.getCurrentUserId(request));
                tTraceGather.setCreatorName(AppUserHelper.getCurrentUserName(request));
                tTraceGather.setDeleteFlag("0");
            }
            if (tTraceQuota != null) {
                switch (tTraceQuota.getQuotaType()) {
                    case "1"://字符
                        String value = request.getParameter(indicatorIds[i] + "Value");
                        tTraceGather.setgValue(value);
                        break;
                    case "2"://数值
                        String value2 = request.getParameter(indicatorIds[i] + "Value");
                        tTraceGather.setgValue(value2);
                        break;
                    case "3"://日期
					/*try {*/
						String timeStr1 = request.getParameter(indicatorIds[i] + "Value");
						if(timeStr1 != null && !"".equals(timeStr1)){
							tTraceGather.setgValue(timeStr1);
						}
					/*} catch (ParseException e) {
						 logger.error("溯源指标值保存日期格式转化错误" + e.getMessage());
                         return AppUtil.returnMapJson("0", "溯源指标值保存日期:" + request.getParameter(indicatorIds[i] + "Value") + "格式转化错误", null);
					}*/
                        break;
                    case "4"://日期时间
                        /*try {*/
                        	String timeStr = request.getParameter(indicatorIds[i] + "Value");
                        	if(timeStr != null && !"".equals(timeStr)){
                        		tTraceGather.setgValue(timeStr + "");
                        	}
                        /*} catch (ParseException e) {
                            logger.error("工艺指标值保存日期时间格式转化错误" + e.getMessage());
                            return AppUtil.returnMapJson("0", "溯源指标值保存日期时间:" + request.getParameter(indicatorIds[i] + "Value") + "格式转化错误", null);
                        }*/
                        break;
                    case "5"://图片
                           try {
                         
                       if (mFile2 != null && mFile2.getOriginalFilename().length() > 0) {
                           //删除原来的图片
                           List<TTraceGatherAtt> attList = tTraceGatherAttMapper.selectByTraceGather(tTraceGather.getId());
                           for (TTraceGatherAtt att2 : attList) {
                        	   tTraceGatherAttMapper.delete(att2);
                           }
                           if (tTraceGather.getId() == null) {
                        	   tTraceGatherMapper.insert(tTraceGather);
                           }
                           TTraceGatherAtt att = new TTraceGatherAtt();//附件表
                            att.settGatherId(tTraceGather.getId());
                            att.setDeptId(AppUserHelper.getCurrentDeptId(request));
                            att.setDeptName(AppUserHelper.getCurrentDeptName(request));
                            att.settEId(AppUserHelper.getCurrentCompanyId(request));
                            Map<String, Object> urlMap = UploadFile.compressUploadedFile(mFile2);
                            att.setTurl(urlMap.get("thumbnails") + "");
                            att.setUrl(urlMap.get("fileName") + "");
                            att.setType("5");
                            att.setCreateTime(new Date());
                            att.setCreatorId(AppUserHelper.getCurrentUserId(request));
                            att.setCreatorName(AppUserHelper.getCurrentUserName(request));
                            att.setDeleteFlag("0");
                            tTraceGatherAttMapper.insert(att);
                        }
                               break;
                        } catch (Exception e) {
                             logger.error("溯源指标值上传图片失败" + e.getMessage());
                               return AppUtil.returnMapJson("0", "溯源指标值上传图片失败", null);
                       }
                     
                    case "6"://音视频
                        try {
                            if (mFile2 != null && mFile2.getOriginalFilename().length() > 0) {
                                List<TTraceGatherAtt> attList2 = tTraceGatherAttMapper.selectByTraceGather(tTraceGather.getId());
                                for (TTraceGatherAtt att2 : attList2) {
                                	tTraceGatherAttMapper.delete(att2);
                                }
                                if (tTraceGather.getId() == null) {
                                	tTraceGatherMapper.insert(tTraceGather);
                                }
                                TTraceGatherAtt att = new TTraceGatherAtt();//附件表
                                att.settGatherId(tTraceGather.getId());
                                att.setDeptId(AppUserHelper.getCurrentDeptId(request));
                                att.setDeptName(AppUserHelper.getCurrentDeptName(request));
                                att.settEId(AppUserHelper.getCurrentCompanyId(request));
                                String urlMap = UploadFile.processUploadedVideo(mFile2);
                                att.setTurl(urlMap);
                                att.setUrl(urlMap);
                                att.setType("6");
                                att.setCreateTime(new Date());
                                att.setCreatorId(AppUserHelper.getCurrentUserId(request));
                                att.setCreatorName(AppUserHelper.getCurrentUserName(request));
                                att.setDeleteFlag("0");
                                tTraceGatherAttMapper.insert(att);
                            }
                           
                            break;
                        } catch (Exception e) {
                            logger.error("溯源指标值上传音频失败" + e.getMessage());
                            return AppUtil.returnMapJson("0", "溯源指标值上传音频失败", null);
                        }
                    default:
                        return AppUtil.returnMapJson("0", "溯源指标中值类型没有定义", null);
                }
                if (tTraceGather.getId()==null) {
                	tTraceGatherMapper.insert(tTraceGather);
                }else{
                	tTraceGatherMapper.updateByPrimaryKeySelective(tTraceGather);
                }
               
                
            } else {
                return AppUtil.returnMapJson("0", "溯源指标对应的id:" + indicatorIds[i] + "没有查询出数据", null);
            }
        }
        return AppUtil.returnMapJson("1", "保存成功!", null);
	}
	
	/**
     * 根据图片路径删除图片
     * @param newFileUrl
     */
    public void deleteFileByUrl(String newFileUrl) {
    	tTraceGatherAttMapper.deleteByUrl(newFileUrl);
    }

	public void indexDelete(Integer recipientId,String[] pid, HttpServletRequest request) {
		Map<String,Object> param = new HashMap<>();
		param.put("deleteFlag", "1");
		for(int i=0; i < pid.length; i++){
			param.put("tQuotaId", pid[i]);
			param.put("recipientId", recipientId);
			tTraceGatherMapper.updateByPid(param);
		}
	}
}
